//
//  UserCentral.m
//  playSerengetiMobile1
//
//  Created by Lita Gratrix on 12/13/09.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "UserCentral.h"
#import "JSON/JSON.h"

#define kViewTag		1		//for tagging our embedded controls for removal at cell recycle time

#define kRecentVisitsSection	0		// for selecting the table section containing recent visits
#define kMostActiveSection		1		// for selecting the table section containing most active users
#define kNewestUsersSection		2		// for selecting the table section containing newest users

#define ROW_HEIGHT_FOR_RECENT	70
#define ROW_HEIGHT_FOR_OTHER	30

static NSString *kSectionTitleKey = @"sectionTitleKey";
static NSString *kSourceKey = @"sourceKey";
static NSString *kViewKey = @"viewKey";

@implementation UserCentral

@synthesize userCentralTableView;
@synthesize recentVisits, mostActive, newestUsers;
@synthesize tableSourceArray;
@synthesize appDelegate;

- (void)viewDidLoad{
	[super viewDidLoad];
	
//	NSLog(@"Entering UserCentral viewDidLoad\n");
	
	self.appDelegate = (playSerengetiMobile1AppDelegate *)[[UIApplication sharedApplication] delegate];
	
	NSArray *currentSubviews = appDelegate.window.subviews;
	UIView *viewToRemove = [currentSubviews objectAtIndex:[currentSubviews count] -1];
	if([viewToRemove isKindOfClass:[MainView class]]){
	    [viewToRemove removeFromSuperview];
	}
	
	
	responseData = [[NSMutableData data] retain];
	NSString *URLString = [NSString stringWithFormat:@"%@user/json", appDelegate.baseURL];
//	NSLog(@"Submit String for UserCentral is %@\n", URLString);
	NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:URLString]];
	[[NSURLConnection alloc] initWithRequest:request delegate:self];
	
	self.recentVisits = [[NSMutableArray alloc] init];
	self.mostActive = [[NSMutableArray alloc] init];
	self.newestUsers = [[NSMutableArray alloc] init];
	self.tableSourceArray = [NSArray arrayWithObjects:
							 [NSDictionary dictionaryWithObjectsAndKeys:
							 @"Recent Visits", kSectionTitleKey,
							 self.recentVisits, kSourceKey,
							 nil],
	
							 [NSDictionary dictionaryWithObjectsAndKeys:
							 @"Most Active Users", kSectionTitleKey,
							 self.mostActive, kSourceKey,
							 nil],
	
							 [NSDictionary dictionaryWithObjectsAndKeys:
							 @"Newest Users", kSectionTitleKey,
							 self.newestUsers, kSourceKey,
							 nil],
							nil];
}

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
}

#pragma mark -
#pragma mark populateViewDataMethods

-(void)populateViewData:(NSDictionary *)parsedData{
	NSMutableArray *recentVisitsArray = [parsedData objectForKey:@"recent"];
	NSMutableArray *mostActiveArray =[parsedData objectForKey:@"mostActive"];
	NSMutableArray *newestUsersArray = [parsedData objectForKey:@"newest"];
	
	[self populateRecentVisits:(NSMutableArray *)recentVisitsArray];
	[self populateMostActive:(NSMutableArray *)mostActiveArray];
	[self populateNewestUsers:(NSMutableArray *)newestUsersArray];
	
	[self.userCentralTableView reloadData];
}

- (void)populateRecentVisits:(NSMutableArray *)recentVisitsArray{
//	NSLog(@"Entering populateRecentVisits\n");
//	NSLog(@"recentVisits array has %d elements\n", [recentVisitsArray count]);
	if([recentVisitsArray count] == 0){
		//Do something
	} else {
		[recentVisits removeAllObjects];
		int i;
		for (i = 0; i < [recentVisitsArray count]; i++){
			Visit *recentVisit = [[Visit alloc] init];
			NSDictionary *recentDic = [recentVisitsArray objectAtIndex:i];
			recentVisit.visitId = [[recentDic objectForKey:@"id"] integerValue];
			NSDictionary *visitUserDic = [recentDic objectForKey:@"user"];
			NSDictionary *visitTeamDic = [recentDic objectForKey:@"team"];
			NSDictionary *visitLocationDic = [recentDic objectForKey:@"location"];
			recentVisit.user = [self populateVisitUser:visitUserDic];
			recentVisit.team = [self populateVisitTeam:visitTeamDic];
			recentVisit.location = [self populateVisitLocation:visitLocationDic];
			
//			NSLog(@"Adding visit %d to recentVisits\n", recentVisit.visitId);
			[recentVisits addObject:recentVisit];
		}
	}
}

- (void)populateMostActive:(NSMutableArray *)mostActiveArray{
//	NSLog(@"Entering populateMostActive\n");
//	NSLog(@"mostActiveArray has %d elements\n", [mostActiveArray count]);
	if([mostActiveArray count] == 0){
		//Do something
	} else {
		[mostActive removeAllObjects];
		int i;
		for (i = 0; i < [mostActiveArray count]; i++){
			User *mostActiveUser = [[User alloc] init];
			NSDictionary *mostActiveDic = [mostActiveArray objectAtIndex:i];
			mostActiveUser.userId = [[mostActiveDic objectForKey:@"id"] integerValue];
			mostActiveUser.name = [mostActiveDic objectForKey:@"name"];
			mostActiveUser.email = [mostActiveDic objectForKey:@"email"];
//			NSLog(@"Adding user %d to mostActive\n");
			[mostActive addObject:mostActiveUser];
		}
	}
}

- (void)populateNewestUsers:(NSMutableArray *)newestUsersArray{
//	NSLog(@"Entering populateNewestUsers\n");
//	NSLog(@"newestUseresArray has %d elements\n", [newestUsersArray count]);
	if([newestUsersArray count] == 0){
		//Do something
	} else {
		[newestUsers removeAllObjects];
		int i;
		for (i = 0; i < [newestUsersArray count]; i++){
			User *newestUser = [[User alloc] init];
			NSDictionary *newestDic = [newestUsersArray objectAtIndex:i];
			newestUser.userId = [[newestDic objectForKey:@"id"] integerValue];
			newestUser.name = [newestDic objectForKey:@"name"];
			newestUser.email = [newestDic objectForKey:@"email"];
//			NSLog(@"Adding user %d to mostActive\n");
			[newestUsers addObject:newestUser];
		}
	}	
}

- (User *)populateVisitUser:(NSDictionary *)visitUserDic {
//	NSLog(@"Entering populateVisitUser\n");
	User *visitUser = [[User alloc] init];
	visitUser.userId = [[visitUserDic objectForKey:@"id"] integerValue];
	visitUser.name = [visitUserDic objectForKey:@"name"];
	return visitUser;
}

- (Team *)populateVisitTeam:(NSDictionary *)visitTeamDic {
//	NSLog(@"Entering populateVisitTeam\n");
	Team *visitTeam = [[Team alloc] init];
	visitTeam.teamId = [[visitTeamDic objectForKey:@"id"] integerValue];
	visitTeam.teamName =[visitTeamDic objectForKey:@"name"];
	return visitTeam;
}

- (Location *)populateVisitLocation:(NSDictionary *)visitLocationDic {
//	NSLog(@"Entering populateVisitLocation\n");
	Location *visitLocation = [[Location alloc] init];
	visitLocation.locationId = [[visitLocationDic objectForKey:@"id"] integerValue];
	visitLocation.locationName = [visitLocationDic objectForKey:@"name"];
	visitLocation.latitude  = [[visitLocationDic objectForKey:@"latitude"] doubleValue];
	visitLocation.longitude  = [[visitLocationDic objectForKey:@"longitude"] doubleValue];
	return visitLocation;
}

#pragma mark -
#pragma mark NSURLConnectionDelegate

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
	[responseData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
	[responseData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
	NSLog(@"Connection failed: %@\n", [error description]);
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
	[connection release];
	
	NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
//	NSLog(@"responseString for UserCentral reads: %@\n", responseString);
	
	[responseData release];
	
	NSDictionary *parsedData = [responseString JSONValue];
	
	[responseString release];
	
	if (parsedData == nil) {
		NSLog(@"Error in returned data.\n");
	} else {
		[self populateViewData:(NSDictionary *)parsedData];
	}
}	

#pragma mark -
#pragma mark UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
	return [tableSourceArray count];
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
	return [[self.tableSourceArray objectAtIndex: section] valueForKey:kSectionTitleKey];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
	//	NSLog(@"Entering tableView:%@ numberOfRowsInSection:%d", tableView, section);
	NSMutableArray *sectionData = [[self.tableSourceArray objectAtIndex:section] valueForKey:kSourceKey];
	//	NSLog(@"number of expected rows: %d.\n", [sectionData count]);
	return [sectionData count];
}

// to determine specific row height for each cell, override this.
// In this example, each row is determined by its subviews that are embedded.
//
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
	if(indexPath.section == kRecentVisitsSection){
		return ROW_HEIGHT_FOR_RECENT;
	} else {
		return ROW_HEIGHT_FOR_OTHER;
	}
}

// to determine which UITableViewCell to be used on a given row.
//
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
	UITableViewCell *cell = nil;
	User *aUser;
	Visit *aVisit;
	
	if(indexPath.section == kRecentVisitsSection){
		aVisit = [[[self.tableSourceArray objectAtIndex: indexPath.section] valueForKey:kSourceKey] objectAtIndex: indexPath.row];
	} else { 
		aUser = [[[self.tableSourceArray objectAtIndex: indexPath.section] valueForKey:kSourceKey] objectAtIndex: indexPath.row];
	}
	
	static NSString *kDisplayCell_ID = @"DisplayCellID";
	cell = [self.userCentralTableView dequeueReusableCellWithIdentifier:kDisplayCell_ID];
	if (cell == nil)
	{
		cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kDisplayCell_ID] autorelease];
		cell.selectionStyle = UITableViewCellSelectionStyleNone;
		cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
	} else {
		// the cell is being recycled, remove old embedded controls
		UIView *viewToRemove = nil;
		viewToRemove = [cell.contentView viewWithTag:kViewTag];
		if (viewToRemove){
			[viewToRemove removeFromSuperview];
		}
	}
	
	UIControl *control = [[self.tableSourceArray objectAtIndex: indexPath.section] valueForKey:kViewKey];
	[cell.contentView addSubview:control];
	
	if(indexPath.section == kRecentVisitsSection){
		NSString *cellTitle = [NSString stringWithFormat:@"%@ checked in at %@ for team %@", aVisit.user.name, aVisit.location.locationName, aVisit.team.teamName];
		cell.textLabel.text = cellTitle;
		cell.textLabel.numberOfLines = 0;
	} else {
		cell.textLabel.text = aUser.name;
	}
	
	return cell;
}

- (void)switchAction:(id)sender
{
	// NSLog(@"switchAction: value = %d", [sender isOn]);
}

- (void)pageAction:(id)sender
{
	// NSLog(@"pageAction: current page = %d", [sender currentPage]);
}

#pragma mark -
#pragma mark UITableViewDelegate

// the table's selection has changed, switch to that item's UIViewController
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
	User *aUser;
	if (indexPath.section == kRecentVisitsSection){
		Visit *aVisit = [[[self.tableSourceArray objectAtIndex:indexPath.section] valueForKey:kSourceKey] objectAtIndex: indexPath.row];
		aUser = aVisit.user;
	} else {
		aUser = [[[self.tableSourceArray objectAtIndex: indexPath.section] valueForKey:kSourceKey] objectAtIndex: indexPath.row];
	}	
	
	UserProfile *aUserProfileView = [[UserProfile alloc] initWithNibName:@"UserProfile" bundle:nil];
	aUserProfileView.userId = aUser.userId;
	[self.view addSubview:aUserProfileView.view];	
	
}


@end
